<template>
  <view class="comment-bg"> 
    <!-- 动态详情卡片 -->
    <view class="post-detail" v-if="postInfo && postInfo.posts_info">
      <view class="post-header" @click="navigateToUserHome(postInfo.posts_user_info.id)">
        <u-avatar :src="globalConfig.site_url+postInfo.posts_user_info.image || '/static/avatar.png'" size="50" />
        <view class="user-info">
          <text class="nickname">{{ postInfo.posts_user_info.nickname }}</text>
          <text class="time">{{  postInfo.posts_info.createtime }}</text>
        </view>
      </view>
      <view class="post-content">{{ postInfo.posts_info.info }}</view>
      <view v-if="postInfo.posts_info.images && postInfo.posts_info.images.length" class="post-images">
        <image v-for="(img, idx) in postInfo.posts_info.images" :key="idx"
          :src="globalConfig.site_url + img || '/static/icons/default-image.png'" mode="aspectFill" class="post-img" />
      </view>
      <view class="post-meta">
        <text class="location">{{ postInfo.posts_info.area_name }}</text>
        <view class="stats">
          <text class="stat-item">{{ postInfo.posts_info.likes_count }} 点赞</text>
          <text class="stat-item">{{ postInfo.posts_info.comments_count }} 评论</text>
          <view class="more-btn" @click.stop="showActionMenu(postInfo.posts_info)">
            <u-icon name="more-dot-fill" size="24" color="#888" />
          </view>
        </view>
      </view>
    </view>
    <!-- 评论列表 -->
    <view class="comment-list">
      <view class="comment-item" v-for="item in commentsList" :key="item.id">
        <u-avatar :src="globalConfig.site_url+item.user_info.image || '/static/avatar.png'" size="48" @click="navigateToUserHome(item.user_info.id)" />
        <view class="comment-content">
          <view class="nickname-row">
            <text class="nickname" @click="navigateToUserHome(item.user_info.id)">{{ item.user_info.nickname || '匿名用户' }}</text>
            <text class="time">{{ item.createtime }}</text>
          </view>
          <view class="text">{{ item.info }}</view>
          <view class="actions">
            <view class="like-btn" @click.stop="handleLike(item)">
              <u-icon name="thumb-up" size="24" :color="item.liked ? '#ff4d4f' : '#888'" />
              <text class="like-count">{{ item.like_count || 0 }}</text>
            </view>
            <view class="reply-btn" @click.stop="setReply(item.id)">
              <u-icon name="chat" size="24" color="#888" />
              <text>回复</text>
            </view>
          </view>
          <!-- 子回复平铺展示 -->
          <view v-if="flatRepliesMap[item.id] && flatRepliesMap[item.id].length" class="flat-replies">
            <view class="reply-row" v-for="reply in flatRepliesMap[item.id]" :key="reply.id">
              <u-avatar :src="globalConfig.site_url+reply.user_info.image || '/static/avatar.png'" size="36" @click="navigateToUserHome(reply.user_info.id)" />
              <view class="reply-content">
                <view class="nickname-row">
                  <text class="nickname">{{ reply.user_info.nickname || '匿名用户' }}</text>
                  <text class="time">{{ formatTime(reply.createtime) }}</text>
                </view>
                <view class="text">
                  <text v-if="reply.parent_user_info" class="reply-to">@{{ reply.parent_user_info.nickname || '匿名用户' }} </text>
                  <text>{{ reply.info }}</text>
                </view>
                <view class="actions">
                  <view class="like-btn" @click.stop="handleLike(reply)">
                    <u-icon name="thumb-up" size="20" :color="reply.liked ? '#ff4d4f' : '#888'" />
                    <text class="like-count">{{ reply.like_count || 0 }}</text>
                  </view>
                  <view class="reply-btn" @click.stop="setReply(reply.id)">
                    <u-icon name="chat" size="20" color="#888" />
                    <text>回复</text>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view v-if="commentsList.length == 0" class="empty-state">
        <text class="empty-text">暂无评论，快来抢沙发吧~</text>
      </view>
      <view v-else-if="commentsList.length > 0" class="no-more">
        没有更多评论了
      </view>
    </view>
    <!-- 底部输入栏 -->
    <view class="input-bar">
      <u-input
        v-model="input"
        :placeholder="replyToCommentId ? '回复@' + getReplyNickname(replyToCommentId) : '说点什么吧…'"
        border="none"
        class="input"
        ref="inputRef"
        maxlength="500"
        confirm-type="send"
        @confirm="submit"
        :focus="inputFocus"
      />
      <u-button type="primary" shape="circle" class="send-btn" @click="submit">发送</u-button>
      <u-icon v-if="replyToCommentId" name="close" size="28" color="#888" @click="cancelReply" style="margin-left:8rpx;" />
    </view>
    <!-- ...actionMenu弹窗等部分保持不变... -->
     <u-popup v-model="actionMenuShow" mode="bottom" :show-arrow="false">
      <view class="action-menu">
        <view class="action-item" v-if="getUserInfo.id == postInfo.posts_user_info.id" @click="handleUpdateVisible">
          <u-icon :name="currentItem.is_show == 1 ? 'eye-off' : 'eye'" size="28" :color="currentItem.is_show == 1 ? '#faad14' : '#00b42a'" />
          <text>{{ currentItem.is_show == 1 ? '设为不可见' : '设为可见' }}</text>
        </view>
        <view class="action-item" v-if="getUserInfo.id == postInfo.posts_user_info.id" @click="handleDeleteDynamic">
          <u-icon name="trash" size="28" color="#ff4d4f" />
          <text>删除动态</text>
        </view>
        <view class="action-item" v-else @click="handleReportDynamic">
          <u-icon name="flag" size="28" color="#faad14" />
          <text>举报动态</text>
        </view>
        <view class="action-item cancel" @click="actionMenuShow = false">
          <u-icon name="close" size="28" color="#888" />
          <text>取消</text>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { getPostsInfo, getComments, saveComments, saveLikes, deleteDynamic, reportDynamic, updateDynamicVisible } from '@/api/dynamic.js'
import { mapGetters, mapState } from 'vuex';

export default {
  name: 'CommentDetail',
  data() {
    return {
      comments: [],
      commentsList: [],
      input: '',
      postInfo: null,
      replyToCommentId: null,
      isSubmitting: false,
      id: '',
      actionMenuShow: false,
      currentItem: null,
      flatRepliesMap: {}, // 新增属性，用于存储扁平化的回复映射
      inputFocus: false, // 控制输入框聚焦
    }
  },
  onLoad(options) {
    this.id = options.id
    this.getPostDetail(options.id)
  },
  computed: {
    ...mapGetters(['getUserInfo']),
    ...mapState({
      globalConfig: state => state.config,
      userLocation: state => state.location,
    })
  },
  methods: {
    formatTime(timestamp) {
      if (!timestamp) return '';
      // 兼容后端返回字符串或数字
      let ts = Number(timestamp);
      if (isNaN(ts) || ts <= 0) return '';
      // 秒级时间戳自动转为毫秒
      if (ts < 10000000000) ts = ts * 1000;
      const date = new Date(ts);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hour = String(date.getHours()).padStart(2, '0');
      const minute = String(date.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hour}:${minute}`;
    },
    getReplyNickname(commentId) {
      // 查找评论或回复的昵称
      for (const item of this.commentsList) {
        if (item.id === commentId) return item.user_info.nickname || '匿名用户';
        if (item.replies && item.replies.length) {
          for (const reply of item.replies) {
            if (reply.id === commentId) {
              return reply.user_info.nickname || '匿名用户';
            }
          }
        }
      }
      return '';
    },
    async getPostDetail(posts_id) {
      try {
        const res = await getPostsInfo({ posts_id: posts_id })
        if (res.data && res.data.code == 1) {
          this.postInfo = res.data.data
          this.getCommentsList()
        } else {
          uni.showToast({ title: res.data.msg || '获取动态详情失败', icon: 'none' })
        }
      } catch (error) {
        uni.showToast({ title: '网络错误', icon: 'none' })
      }
    },
    async getCommentsList() {
      if (!this.postInfo || !this.postInfo.posts_info || !this.postInfo.posts_info.area_id) {
        return;
      }
      uni.showLoading({ title: '加载中...' })
      try {
        const res = await getComments({ posts_id: this.id })
        this.loading = false;
        if (res.data && res.data.code == 1) {
          const comments = res.data.data || [];
          // 扁平化所有嵌套 replies/children 到一级
          const flatComments = [];
          const collectAllReplies = (item) => {
            flatComments.push(item);
            // 递归收集 replies 和 children
            if (Array.isArray(item.replies) && item.replies.length) {
              item.replies.forEach(child => collectAllReplies(child));
            }
            if (Array.isArray(item.children) && item.children.length) {
              item.children.forEach(child => collectAllReplies(child));
            }
          };
          comments.forEach(comment => {
            comment.like_count = Number(comment.like_count) || 0;
            comment.liked = comment.liked || false;
            collectAllReplies(comment);
          });
          // 一级评论
          this.commentsList = flatComments.filter(item => !item.parent_comment_id);
          // 所有回复（parent_comment_id 映射）
          this.flatRepliesMap = {};
          flatComments.forEach(item => {
            if (item.parent_comment_id) {
              if (!this.flatRepliesMap[item.parent_comment_id]) this.flatRepliesMap[item.parent_comment_id] = [];
              this.flatRepliesMap[item.parent_comment_id].push(item);
            }
          });
        } else {
          uni.showToast({ title: res.data.msg || '获取评论失败', icon: 'none' })
        }
      } catch (error) {
        uni.showToast({ title: '网络错误', icon: 'none' })
      } finally {
        uni.hideLoading()
      }
    },
    setReply(commentId) {
      this.replyToCommentId = commentId;
      this.inputFocus = false;
      this.$nextTick(() => {
        this.inputFocus = true;
        // 滚动到输入框区域
        uni.createSelectorQuery().select('.input-bar').boundingClientRect().exec(res => {
          if (res[0]) {
            uni.pageScrollTo({ scrollTop: res[0].top - 100, duration: 300 });
          }
        });
      });
    },
    cancelReply() {
      this.replyToCommentId = null;
      this.input = '';
      this.inputFocus = false;
    },
    navigateToUserHome(userId) {
      if (!userId) {
        uni.showToast({ title: '用户信息获取失败', icon: 'none' });
        return;
      }
      uni.navigateTo({ url: `/pages/other/profile?id=${userId}` })
    },
    showActionMenu(item) {
      this.currentItem = item;
      this.actionMenuShow = true;
    },
    async handleUpdateVisible() {
      console.log(this.currentItem, 'this.currentItem');
      
      const newVisible = this.currentItem.is_show == 1 ? 2 : 1;
      try {
        const res = await updateDynamicVisible({ posts_id: this.currentItem.id, is_show: newVisible });
        if (res.data && res.data.code == 1) {
          this.currentItem.is_show = newVisible;
          this.postInfo.posts_info.is_show = newVisible;
          uni.showToast({ title: newVisible == 1 ? '已设为可见' : '已设为不可见', icon: 'success' });
          this.actionMenuShow = false;
        } else {
          uni.showToast({ title: res.data.msg || '操作失败', icon: 'none' });
        }
      } catch (error) {
        uni.showToast({ title: '网络错误，操作失败', icon: 'none' });
      }
    },
    async handleDeleteDynamic() {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这条动态吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              const res = await deleteDynamic({ posts_id: this.currentItem.id });
              if (res.data && res.data.code == 1) {
                uni.showToast({ title: '删除成功', icon: 'success' });
                uni.navigateBack();
              } else {
                uni.showToast({ title: res.data.msg || '删除失败', icon: 'none' });
              }
            } catch (error) {
              uni.showToast({ title: '网络错误，删除失败', icon: 'none' });
            }
          }
        }
      });
    },
    async handleReportDynamic() {
      uni.showModal({
        title: '举报动态',
        content: '确定要举报这条动态吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              const res = await reportDynamic({ posts_id: this.currentItem.id, reason: 'inappropriate_content' });
              if (res.data && res.data.code == 1) {
                uni.showToast({ title: '举报成功，我们会尽快处理', icon: 'success' });
                this.actionMenuShow = false;
              } else {
                uni.showToast({ title: res.data.msg || '举报失败', icon: 'none' });
              }
            } catch (error) {
              uni.showToast({ title: '网络错误，举报失败', icon: 'none' });
            }
          }
        }
      });
    },
    async handleLike(item) {
      const newType = item.liked ? 2 : 1;
      item.liked = !item.liked;
      item.like_count += newType == 1 ? 1 : -1;
      try {
        const res = await saveLikes({ comment_id: item.id, type: newType });
        if (res.data && res.data.code !== 1) {
          item.liked = !item.liked;
          item.like_count += newType == 1 ? -1 : 1;
          uni.showToast({ title: res.data.msg || '点赞失败', icon: 'none' });
        }
      } catch (error) {
        item.liked = !item.liked;
        item.like_count += newType == 1 ? -1 : 1;
        uni.showToast({ title: '网络错误，无法操作', icon: 'none' });
      }
    },
    async submit() {
      const comment = this.input.trim();
      if (!comment) return uni.showToast({ title: '请输入内容', icon: 'none' });
      if (comment.length > 500) return uni.showToast({ title: '评论内容不能超过500字', icon: 'none' });
      if (this.isSubmitting) return;

      this.isSubmitting = true;
      try {
        if (!this.postInfo || !this.postInfo.posts_info) {
          uni.showToast({ title: '动态信息加载中...', icon: 'none' });
          return;
        }

        const params = {
          posts_id: this.id,
          info: this.input.trim()
        };

        // 仅在回复评论时添加parent_comment_id参数
        if (this.replyToCommentId) {
          params.parent_comment_id = this.replyToCommentId;
        }

        const res = await saveComments(params);
        if (res.data && res.data.code == 1) {
          uni.showToast({ title: '评论成功', icon: 'success' });
          this.input = '';
          this.replyToCommentId = null;
          this.inputFocus = false;
          // 评论成功后刷新第一页评论
          this.getCommentsList();
        } else {
          uni.showToast({ title: res.data.msg || '评论失败', icon: 'none' });
        }
      } catch (error) {
        uni.showToast({ title: '网络错误，评论失败', icon: 'none' });
      } finally {
        this.isSubmitting = false;
      }
    }
  }
}
</script>

<style scoped>
.comment-bg {
  min-height: 100vh;
  background: #18181a;
  display: flex;
  flex-direction: column;
}
.top-bar {
  display: flex;
  align-items: center;
  padding: 0 32rpx;
  background: transparent;
}
.title {
  font-size: 36rpx;
  font-weight: bold;
  margin-left: 24rpx;
  color: #1677ff;
}
.post-detail {
  background: #23232b;
  border-radius: 24rpx;
  box-shadow: 0 4rpx 16rpx rgba(0,0,0,0.12);
  margin: 32rpx 24rpx 0;
  padding: 32rpx 24rpx;
  color: #fff;
}
.post-header {
  display: flex;
  align-items: center;
  margin-bottom: 24rpx;
}
.user-info {
  margin-left: 16rpx;
}
.post-content {
  font-size: 30rpx;
  color: #fff;
  margin-bottom: 24rpx;
  line-height: 1.6;
}
.post-images {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
  margin-bottom: 24rpx;
}
.post-img {
  width: 200rpx;
  height: 200rpx;
  border-radius: 16rpx;
}
.post-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 24rpx;
  color: #888;
  padding-top: 16rpx;
  border-top: 1px dashed #f0f0f0;
}
.location {
  display: flex;
  align-items: center;
}
.stats {
  display: flex;
  gap: 24rpx;
}
.stat-item {
  display: flex;
  align-items: center;
}
.comment-list {
  flex: 1;
  padding: 32rpx 24rpx 140rpx 24rpx;
}
.comment-item {
  display: flex;
  align-items: flex-start;
  gap: 16rpx;
  margin-bottom: 24rpx;
  padding: 24rpx;
  background: #23232b;
  border-radius: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.08);
  color: #fff;
}
.comment-content {
  flex: 1;
}
.nickname-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8rpx;
}
.nickname {
  font-size: 26rpx;
  font-weight: 500;
  color: #fff;
}
.time {
  font-size: 22rpx;
  color: #bbb;
}
.text {
  font-size: 26rpx;
  color: #fff;
  line-height: 1.5;
  margin-bottom: 16rpx;
  word-break: break-all;
}
.actions {
  display: flex;
  gap: 32rpx;
  font-size: 22rpx;
  color: #bbb;
}
.like-btn, .reply-btn {
  display: flex;
  align-items: center;
  gap: 6rpx;
}
.flat-replies {
  margin-top: 16rpx;
  padding-left: 0;
  border-left: none;
}
.reply-row {
  display: flex;
  align-items: flex-start;
  gap: 12rpx;
  margin-bottom: 12rpx;
  background: #23232b;
  border-radius: 16rpx;
  padding: 16rpx;
  color: #fff;
}
.reply-content {
  flex: 1;
}
.reply-to {
  color: #7bdffe;
  font-weight: 500;
}
.empty-state {
  text-align: center;
  padding: 80rpx 0;
}
.empty-text {
  font-size: 28rpx;
  color: #bbb;
}
.no-more {
  text-align: center;
  font-size: 24rpx;
  color: #bbb;
  padding: 32rpx 0;
}
.input-bar {
  display: flex;
  gap: 16rpx;
  padding: 24rpx 32rpx;
  background: #23232b; /* 改为深色，与主卡片一致 */
  border-top: 1px solid #333;
  align-items: center;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 999;
}
.input {
  flex: 1;
  background: #18181a; /* 深色输入框背景 */
  color: #fff; /* 输入文字白色 */
  border-radius: 24rpx;
  padding: 0 24rpx;
  font-size: 26rpx;
}
.send-btn {
  color: #fff;
  border: none; 
  padding: 12rpx 24rpx;
  border-radius: 20rpx;
  font-size: 26rpx;
}
.action-menu {
  background: #23232b;
  /* border-top-left-radius: 24rpx;
  border-top-right-radius: 24rpx; */
  padding: 24rpx 0;
}
.action-item {
  padding: 16rpx 32rpx;
  font-size: 28rpx;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
}
.action-item:hover {
  background: rgba(255, 255, 255, 0.1);
}
</style>
